import Request from './core/Request';
import { Toast } from '@/utils/uni/prompt';
import { ResultEnum } from '@/enums/httpEnum';

const HEADER = {
  'Content-Type': 'application/json;charset=UTF-8;',
  Accept: 'application/json, text/plain, */*',
};

function createRequest() {
  return new Request({
    baseURL: 'http://192.168.0.123',
    header: HEADER,
    custom: {
      auth: true,
    },
  });
}

const axios = createRequest();

// 请求拦截器
axios.interceptors.request.use(
  (options: any) => {
    // if(options.custom?.auth) {
    //   const authStore = useAuthStore();
    //   if(!authStore.isLogin) {
    //     Toast('请先登录');
    //     // token不存在跳转到登录页
    //     return Promise.reject(options);
    //   }
    //   options.header = assign(options.header, {
    //     authorization: `Bearer ${ authStore.getToken }`,
    //   });
    // }
    return options;
  },
  (options: any) => Promise.reject(options),
);

// 响应拦截器
axios.interceptors.response.use(
  async (response: any) => {
    const { data: resData } = response;
    const { code, msg, result } = resData;

    if (code === ResultEnum.SUCCESS) {
      return result as any;
    }
    Toast(msg);
    return Promise.reject(resData);
  },
  (response: any) =>
    // 请求错误做点什么。可以使用async await 做异步操作
    Promise.reject(response),
);

export default axios;
